package com.xmotor.testjavaxvalidation.controller;

import com.xmotor.testjavaxvalidation.exception.BusinessException;
import com.xmotor.testjavaxvalidation.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class ExceptionHandlerContrller extends BaseController{

    // 方式一
//    @ExceptionHandler(MethodArgumentNotValidException.class)
//    public Object exceptionHandler(MethodArgumentNotValidException e) {
//        BindingResult bindingResult = e.getBindingResult();
//        List<ObjectError> allErrors = bindingResult.getAllErrors();
//        Map<String,Object> map = new HashMap<>();
//        allErrors.stream().forEach(objectError -> {
//            FieldError fieldError = (FieldError)objectError;
//            map.put("code",1);
//            map.put("msg",fieldError.getDefaultMessage());
//        });
//        return map;
//    }
//
//
//    @ExceptionHandler(ConstraintViolationException.class)
//    public Object exceptionHandler(ConstraintViolationException e) {
//        Map<String,Object> map = new HashMap<>();
//        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
//        for(ConstraintViolation<?> item:violations){
//            map.put("code",1);
//            map.put("msg",item.getMessage());
//        }
//
//        return map;
//    }



    //方式二
//    @ExceptionHandler(Exception.class)
//    public Object exceptionHandler(Exception e) {
//        System.out.println("发生异常："+e.getMessage());
//        Map<String,Object> map = new HashMap<>();
//        if(e instanceof ConstraintViolationException){
//            ConstraintViolationException exs = (ConstraintViolationException)e;
//            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
//            for(ConstraintViolation<?> item:violations){
//                map.put("code",1);
//                map.put("msg",item.getMessage());
//            }
//
//            return map;
//        }
//
//        if(e instanceof MethodArgumentNotValidException){
//            MethodArgumentNotValidException exs = (MethodArgumentNotValidException)e;
//            BindingResult bindingResult = exs.getBindingResult();
//            for(FieldError fieldError :bindingResult.getFieldErrors()){
//                map.put("code",1);
//                map.put("msg",fieldError.getDefaultMessage());
//            }
//
//            return map;
//        }
//
//        map.put("code",1);
//        map.put("msg","服务器异常!");
//        return map;
//    }


    /**
     * 非法参数验证异常
     * JSON(application/json) 请求方式
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        return fail(fieldError.getDefaultMessage());
    }

    /**
     * 非法参数验证异常
     * x-www-form-urlencoded 请求方式
     * @param exception
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public R bindException(BindException exception) {
        String defaultMessage = exception.getBindingResult().getFieldError().getDefaultMessage();
        return fail(StringUtils.isBlank(defaultMessage) ? "参数异常" : defaultMessage);
    }

    /**
     * 处理请求单个参数不满足校验规则的异常信息
     * @param exception
     * @return
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public R constraintViolationException(ConstraintViolationException exception) {
        Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
        ConstraintViolation constraintViolation = (ConstraintViolation) violations.toArray()[0];
        String defaultMessage = constraintViolation.getMessage();
        return fail(StringUtils.isBlank(defaultMessage) ? "参数异常" : defaultMessage);
    }

    /**
     * 自定义业务异常处理器
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public R businessExceptionHandler(BusinessException e){
        return fail(e.getCode(),e.getMsg());
    }
}
